/****************************************************
 * Description: ServiceImpl for 角色
 * Copyright:   Copyright (c) 2013
 * Company:     beiwaionline
 * @author      bfsu
 * @version     1.0
 * @see
	HISTORY
 *  2013-08-08 bfsu Create File
 **************************************************/

package com.bfsuol.bfsuolframework.security.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.security.PrivilegeService;
import com.bfsuol.bfsuolframework.security.dao.RoleMapper;
import com.bfsuol.bfsuolframework.security.dao.RolePrivilegeMapper;
import com.bfsuol.bfsuolframework.security.dao.Role;
import com.bfsuol.bfsuolframework.security.dao.RolePrivilege;
import com.bfsuol.bfsuolframework.security.entity.dto.Function;
import com.bfsuol.bfsuolframework.security.entity.dto.Privilege;
import com.bfsuol.bfsuolframework.security.entity.dto.TreeNode;
import com.bfsuol.bfsuolframework.security.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper,Role> implements RoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RolePrivilegeMapper rolePrivilegeMapper;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#listpri(java.lang.Long)
	 */
	public List<TreeNode> listpri(Long roleid) {
		// 1.得到角色
		Role role = roleMapper.selectById(roleid);

		// root
		List<TreeNode> list = new ArrayList<TreeNode>();
		TreeNode root = new TreeNode();
		root.setText(role.getTitle());
		root.setState("open");
		root.setId("rootNode");
		root.setNodes(ptoTree(findPrivileges(), roleid));

		list.add(root);

		return list;
	}

	private Collection<Privilege> findPrivileges() {
		return PrivilegeService.getPrivileges();
	}

	private List<TreeNode> ptoTree(Collection<Privilege> privileges, Long roleid) {
		List<TreeNode> list = new ArrayList<TreeNode>();
		if (privileges == null)
			return list;

		TreeNode node;
		for (Privilege p : privileges) {
			node = new TreeNode();
			node.setText(p.getTitle());
			node.setId(p.getCode());
			Map<String,Object> map = ftoTree(p.getCode(), roleid);
			node.setNodes((List<TreeNode>) map.get("list"));
			node.setChecked(map.get("flag")==null?false:((Boolean)map.get("flag")));
			list.add(node);
		}

		return list;
	}

	private Map<String,Object> ftoTree(String pcode, Long roleid) {
		Map<String,Object> map = new HashMap<String, Object>();
		List<TreeNode> list = new ArrayList<TreeNode>();
		
		Privilege privilege = PrivilegeService.getPrivilege(pcode);
		if (privilege == null)
			return map;
		Collection<Function> functions = privilege.getFunctions();
		if (functions == null)
			return map;
		List<String> funs = new ArrayList<String>();
		RolePrivilege rolePrivilege = rolePrivilegeMapper.findByRolePri(roleid,pcode);
		if (rolePrivilege != null)
			funs = rolePrivilege.getFunctions();

		TreeNode node;
		Integer num = 0;
		for (Function f : functions) {
				if(StringUtils.isBlank(f.getTitle())){
					continue;
				}
				node = new TreeNode();
				node.setText(f.getTitle());
				node.setId(f.getCode());
				if (checkFun(f, funs)){
					node.setChecked(true);
					num++;
				}
				list.add(node);
		}
		if(num != 0){
			map.put("flag", true);
		}else{
			map.put("flag", false);
		}
		map.put("list", list);
		return map;
	}

	private boolean checkFun(Function f, List<String> funs) {
		if (f.getCode().equals("default"))
			return true;
		for (String s : funs) {
			if (s.equals(f.getCode()))
				return true;
		}

		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#savepri(java.lang.Long)
	 */
	public String savepri(Long roleid, String codes) {
		// 1.得到勾选的对象
		Map<String, String> map = new HashMap<String, String>();
		try {
			if (!StringUtils.isBlank(codes)) {
				String[] pris = codes.split("%%%%");
				for(Privilege p : findPrivileges()){
					String pcode = "";
					StringBuffer ccode = new StringBuffer(); 
					for (String pri : pris) {
						if(pri.split("===")[0].equals(p.getCode())){
							pcode = p.getCode();
							ccode.append(pri.split("===")[1]+"|");
						}
					}
					if(pcode != ""){
						map.put(pcode, ccode.substring(0,ccode.length()-1).toString());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "格式化权限树失败！";
		}

		// 2.更新权限:删除已有role下的rp，添加
		rolePrivilegeMapper.delByRole(roleid);
		RolePrivilege rolePrivilege;
		Privilege privilege;
		for (String pri : map.keySet()) {
			privilege = PrivilegeService.getPrivilege(pri);
			if (privilege == null)
				return "查找权限错误！";

			rolePrivilege = new RolePrivilege();
			rolePrivilege.setRole(new Role(roleid));
			rolePrivilege.setRoleId(roleid);
			rolePrivilege.setPrivilegeCode(privilege.getCode());
			rolePrivilege.setPrivilegeTitle(privilege.getTitle());
			rolePrivilege.setFunctionList(map.get(pri));

			rolePrivilegeMapper.insert(rolePrivilege);
		}

		return "suc";
	}



	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#getRolesNotInGroup(
	 * java.lang.Long, java.lang.String,
	 * com.bfsuolframework.core.controller.support.Pagination)
	 */
	public Pagination findRolesNotInGroup(Long groupId, String roleName,
			Pagination page) {
		//return roleDAO.findRolesNotInGroup(groupId, roleName, page);
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#checkCode(java.lang
	 * .String)
	 */
	public boolean checkCode(Role role) {
		//return roleDAO.checkCode(role);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#checkDel(java.lang.
	 * Long)
	 */
	public String checkDel(Long id) {
		/*Role role = roleDAO.getById(id);
		Collection<BaseUser> users = role.getUsers();
		Collection<RolePrivilege> privileges = role.getPrivileges();

		StringBuilder sb = new StringBuilder();
		if (users != null && users.size() != 0)
			sb.append(",用户");
		if (!roleDAO.checkGroups(id))
			sb.append(",用户组");
		if (privileges != null && privileges.size() != 0)
			sb.append(",权限");

		if ("".equals(sb.toString())) {
			return "suc";
		} else {
			return "删除失败，请先删除与角色相关的【" + sb.toString().replaceFirst(",", "")
					+ "】信息！";
		}*/
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#deleteAll(java.lang
	 * .Long[])
	 */
	public String deleteAll(Long[] ids) {
		/*int total = ids.length;
		if (total == 0)
			return "请选择要删除的角色！";

		int userNum = 0;
		int groupNum = 0;
		int priNum = 0;
		for (Long id : ids) {
			if (!roleDAO.checkUsers(id)) {
				userNum++;
				continue;
			}
			if (!roleDAO.checkGroups(id)) {
				groupNum++;
				continue;
			}
			if (!roleDAO.checkPris(id)) {
				priNum++;
				continue;
			}

			roleDAO.delete(id);
			BfsuolLogger.data("删除角色，ID：" + id);
		}

		int failNum = userNum + groupNum + priNum;

		StringBuilder sb = new StringBuilder();
		if (failNum != total)
			sb.append("成功删除" + (total - failNum) + "条！<br>");
		if (failNum != 0)
			sb.append("删除失败" + failNum + "条:<br>");
		if (userNum != 0)
			sb.append("因与用户有关联而失败" + userNum + "条！<br>");
		if (groupNum != 0)
			sb.append("因与用户组有关联而失败" + groupNum + "条！<br>");
		if (priNum != 0)
			sb.append("因与权限有关联而失败" + priNum + "条！<br>");

		return sb.toString();*/
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#findPrivilegeByRole
	 * (java.lang.Long)
	 */
	public List<RolePrivilege> findPrivilegeByRole(Long roleId) {
		//return rolePrivilegeDAO.findRolePrivilegesByRoleId(roleId);
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * RoleService#getByCode(java.lang
	 * .String)
	 */
	public Role getByCode(String roleCode) {
		//return roleDAO.getByCode(roleCode);
		return null;
	}
}